﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HostsManager
{
    public static class StringUtil
    {
        public static String CompactSpaces(this String text)
        {
            String result = text;

            while (result.Contains("  "))
                result = result.Replace("  ", " ");

            return result;
        }

        public static String CompactBlankLines(this String text)
        {
            String result = text;

            while (result.Contains(Environment.NewLine + Environment.NewLine + Environment.NewLine))
                result = result.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, Environment.NewLine + Environment.NewLine);

            return result;
        }

        public static String RemoveBlankLines(this String text)
        {
            String result = text;

            while (result.Contains(Environment.NewLine + Environment.NewLine))
                result = result.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);

            return result;
        }

        public static IEnumerable<string> SplitPreservingQuotes(this string value, char delimiter)
        {
            Regex csvPreservingQuotedStrings = new Regex(string.Format("(\"[^\"]*\"|[^{0}])+", delimiter));
            var values =
                csvPreservingQuotedStrings.Matches(value)
                .Cast<Match>()
                .Select(m => m.Value.Trim().Replace("\"", string.Empty))
                .Where(v => !string.IsNullOrWhiteSpace(v));
            return values;
        }
    }
}
